<script setup lang="ts">
import VChart from 'vue-echarts'
import type { VChartInstance } from '@/types'
import { useChartToolboxDataView } from '@/mixins/MixinChartToolboxDataView'
import { useChartTooltipTheme, useChartTooltipAxisPointerLineStyle } from '@/mixins/MixinChartTooltipTheme'
import { useChartAutoResize } from '@/mixins/MixinChartAutoResize'

const props = defineProps<{
  data: any[]
  name: string
}>()

const {
  dataView,
} = useChartToolboxDataView(() => ({
  dataViewFirstCellName: '时间',
  optionToContent: (opt: any, g: (d: any[]) => string | HTMLElement) => {
    const source = (opt.dataset[0]?.source || []) as any[]
    let result: any[] = []
    if (source.length > 0) {
      const head = source[0] || []
      const body = source.slice(1) || []
      result = [
        ['时间', ...body.map(v => v[0])],
        ...head.slice(1).map(((v: any, i: number) => {
          return [v, ...body.map(vv => vv.slice(1)[i] ?? '-')]
        })),
      ]
    }
    return g(result)
  },
}))
const tooltipTheme = useChartTooltipTheme()
const max = computed(() => {
  const d = props.data[1]?.slice(1) as number[]
  return d.reduce((a, b) => Math.max(a, b), 0)
})
const chartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      valueFormatter: (value: number) => `${value} 次`,
      axisPointer: {
        type: 'cross',
        ...useChartTooltipAxisPointerLineStyle(),
      },
      ...tooltipTheme,
    },
    grid: {
      top: 50,
      left: 50,
      right: 50,
      bottom: 20,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
    },
    yAxis: {
      type: 'value',
      max: unref(max),
    },
    series: [
      {
        type: 'bar',
        seriesLayoutBy: 'row',
        markPoint: {
          label: {
            color: '#fff',
          },
          emphasis: {
            label: {
              color: '#fff',
            },
          },
          data: [
            { type: 'max', name: '最大值' },
          ],
        },
      },
    ],
    toolbox: {
      show: true,
      top: 10,
      right: 20,
      feature: {
        magicType: {
          type: ['bar', 'line'],
        },
        dataView: unref(dataView),
      },
    },
    dataset: {
      source: props.data || [],
    },
  }
})

const chartRef = ref<VChartInstance>()
const { theme } = storeToRefs(useDesignStore())

function resize(width?: number, height?: number) {
  chartRef.value?.resize({
    width,
    height,
  })
}

useChartAutoResize(chartRef)

defineExpose({
  resize,
})
</script>

<template>
  <VChart
    ref="chartRef"
    :option="chartOption" :init-options="{
      locale: 'zh',
    }" :theme="theme"
    style="min-height: 240px"
  />
</template>
